-- UIChooseEquip
-- Create by huanghr
-- 选择合成

-- UIChooseEquip继承自Layer
UIChooseEquip = class("UIChooseEquip", function(equipId)
    return cc.Layer:create();
end);

function UIChooseEquip.create(equipId)
    return UIChooseEquip.new(equipId);
end

local PAGE_LIST = {1, 2, 3};

-- 构造函数
function UIChooseEquip:ctor(equipId)
    -- 初始化
    self:setName("UIChooseEquip");
    local node = cc.CSLoader:createNode("layout/risker_equip/ChooseSpell.csb");
    self:addChild(node);
    self.node = node;

    self.equipId = equipId;

    self.CT = node:getChildByName("CT");
    self.BT = node:getChildByName("BT");

    self.page = 1;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册点击事件
    self:registerTouchEvent();

    -- 编辑各个页面的卷轴
    self:initData();

    -- 标签页
    self:redrawTabs();

    -- 重绘
    self:redraw();

    -- 注册事件回调
    self:registerEventCallback();

    -- 适配
    self:resize();
end

-- 注册事件回调
function UIChooseEquip:registerEventCallback()
    -- 锻造宝物成功事件
    EventMgr.register("UIChooseEquip", event.FORGE_SUCCESS, function(args)
         self:redraw();
         self:playForgeSuccessEffect(args);
    end);

    -- 显示TOPMENU
    EventMgr.register("UIChooseEquip", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIChooseEquip" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
            UIMgr:getCurrentScene().topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then

            -- 还原TopMenu的ZOrder
            local topMenu = UIMgr.getCurrentScene().topMenu;
            if topMenu then
                topMenu:setVisible(self.oldVisible);
                topMenu:setLocalZOrder(self.oldZOrder);
            end

            cclog("UIChooseEquip 界面析构清理");

            EventMgr.removeAll("UIChooseEquip");
        elseif ev == "enter" then
            -- 临时调高TOP_MENU的ZOrder
            local topMenu = UIMgr:getCurrentScene().topMenu;
            self.oldVisible = topMenu:isVisible();
            UIMgr.getCurrentScene().topMenu:setVisible(true);
            self.oldZOrder = topMenu:getLocalZOrder();
        end
    end);
end

-- 编辑每页的数据
function UIChooseEquip:initData()
    -- 初始化
    local equips = {};

    -- 获得各阶位的卷轴ID
    for k, page in pairs(PAGE_LIST) do
        equips[page] = FormulaM.invoke("GET_SIX_RANK_TREASURE", page);
    end

    self.equips = equips;
end

-- 绘制标签页
function UIChooseEquip:redrawTabs()
    local tabNode = findChildByName(self.node, "CT/tab");

    -- 标签页数量
    local tabNum = #PAGE_LIST;

    -- 先移除旧的标签
    tabNode.rows = {};
    tabNode:removeAllChildren();

    -- 根据tab数据，生成新标签
    local widget = replaceNodeWithWidget(cc.CSLoader:createNode("layout/tab/tab.csb"));

    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    for i = 1, tabNum do
        local child = widget:clone();
        child:setName("tab" .. i);
        child.index = i;

        self:registerTabTouchEvent(child);

        -- 计算单元格坐标
        -- 这个坐标将是单元格的描点所在
        local x = (i - 1) * 68 + 55;
        local y = 75;

        child:setPositionX(x);
        child:setPositionY(y);

        local tabLight = findChildByName(child, "light");
        local tabImage = findChildByName(child, "tab");
        tabImage.page = i;

        tabLight:setScaleX(0.7);
        tabImage:setScaleX(0.7);

        local tabText = findChildByName(child, "text");
        local tabIcon = findChildByName(child, "icon");
        TextStyleM.setTextStyle(tabText, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        local rankName = FormulaM.invoke("GET_ITEM_RANK_NAME", i);
        tabText:setString(rankName);

        if i == 1 then
            tabLight:setVisible(true);
            -- tabImage:loadTexture(getTabIconPath("red"));

            tabIcon:setColor(normalColor);
            tabIcon:setVisible(false);
            tabImage:setColor(normalColor);
        else
            tabLight:setVisible(false);

            tabIcon:setColor(blendColor);
            tabIcon:setVisible(false);
            tabImage:setColor(blendColor);
        end

        tabNode:addChild(child)
        table.insert(tabNode.rows, child)
    end

    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        tab:setPositionY(tab:getPositionY() + 100);
    end

    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 页签动画效果
function UIChooseEquip:playTabEffect()
    local tabNode = findChildByName(self.node, "CT/tab");
    -- 带窗口动画播放结束后，页签从上面往下掉
    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        local pos = cc.p(tab:getPosition());
        local delay = cc.DelayTime:create(0.15 * (i - 1));
        local moveDown = cc.MoveTo:create(0.15, cc.p(pos.x, pos.y - 100 - 5));
        local moveBack = cc.MoveTo:create(0.15, cc.p(pos.x, pos.y - 100));
        local action = cc.Sequence:create(delay, moveDown, moveBack);
        tab:runAction(action);
    end
end

-- 注册标签页点击回调
function UIChooseEquip:registerTabTouchEvent(node)
    -- 节点
    local tabImage = node:getChildByName("tab");
    local tabLight = node:getChildByName("light");
    local tabIcon = node:getChildByName("icon");
    local tabNode = findChildByName(self.node, "CT/tab");

    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 去除其它高亮
            for i = 1, #tabNode.rows do
                tabNode.rows[i]:getChildByName("light"):setVisible(false);
                tabNode.rows[i]:getChildByName("tab"):setColor(blendColor);
                tabNode.rows[i]:getChildByName("icon"):setColor(blendColor);
            end
            -- 设置本身高亮
            tabLight:setVisible(true);
            tabImage:setColor(normalColor);
            tabIcon:setColor(normalColor);

            self.page = sender.page;
            self:redraw();
        end
    end

    tabImage:addTouchEventListener(onClick);
end

-- 注册点击事件
function UIChooseEquip:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIChooseEquip");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 重绘
function UIChooseEquip:redraw()
    -- 绘制标题
    local titleLabel = findChildByName(self.CT, "title_label");
    local subTitle = findChildByName(self.CT, "sub_title");

    local title = ItemM.query(self.equipId, "name");

    -- 设置标题文本
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(title);

    -- 设置副文本标题
    local subText = getLocStr("choose_forge_equip");
    TextStyleM.setSubheadStyle(subTitle);
    subTitle:setString(subText);

    -- 当前中间的图标
    local equipNode = findChildByName(self.CT, "item");

    -- 重绘当前页面，当前阶位的所有卷轴
    local equipList = self.equips[self.page];

    local itemNode = cc.CSLoader:createNode("layout/risker_equip/Equip.csb");
    -- 循环复用
    local widget = replaceNodeWithWidget(itemNode);

    -- 装备图标
    local equip = widget:clone();
    local equipIcon = findChildByName(equip, "icon");
    local frameBg = findChildByName(equip, "bg");
    frameBg:setVisible(false);
    local equipIconPath = getItemIconPath(ItemM.query(self.equipId, "icon"));
    equipIcon:loadTexture(equipIconPath);
    equipNode:addChild(equip);

    self.items = {};
    local i = 1;

    for k, v in pairs(equipList) do
        local icon = ItemM.query(v, "icon");
        local iconPath = getItemIconPath(icon);

        local equipItem = widget:clone();
        local iconNode = findChildByName(equipItem, "icon");
        local bg = findChildByName(equipItem, "bg");
        iconNode:loadTexture(iconPath);

        if not RiskerEquipM.canForgeTreasure(v) then
            setGrayTransMode(iconNode, true);
        else
            playBubbleAnima2(iconNode, false, 1, 0.8 , true);
        end

        self:registerIconTouchEvent(bg);
        bg.classId = v;

        local item = findChildByName(self.CT, "item_" .. i);

        item:removeAllChildren();
        item:addChild(equipItem);

        table.insert(self.items, equipItem);

        i = i + 1;
    end
end

--
function UIChooseEquip:registerIconTouchEvent(iconNode)
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            require "game/ui/form/risker_equip/UICompoundTreasure";
             -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UICompoundTreasure");
            local uiForm = UICompoundTreasure.create(sender.classId);
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end

    iconNode:addTouchEventListener(onClick);
end

function UIChooseEquip:playForgeSuccessEffect(args)

    local items = self.items or {};
    for k, item in pairs(items) do

        local bg = findChildByName(item, "bg");
        if bg.classId == args.treasure_id then

            bg:removeAllChildren();

            if type(args.amount) == "number" and args.amount > 1 then
                playEffect(bg, 1231, 93, 9,  nil, 0.82);
            else
                playEffect(bg, 1180, 93, 9,  nil, 0.82);
            end

            -- 文字提示
            local name = ItemM.query(args.treasure_id, "name");
            alert(string.format(getLocStr("compound_spell_tip"), name, args.amount));
        end
    end

end

-- 适配
function UIChooseEquip:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end